<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\RegisterRequest;
use App\Models\Role;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class RegisterController extends Controller
{
    /**
     * 注册
     * @param RegisterRequest $request
     * @return mixed
     * @throws \Exception
     */
    public function store(RegisterRequest $request)
    {
        try {
            DB::beginTransaction();
            $data = $request->only(['name', 'nickname']);
            $data = array_merge($data, ['password' => bcrypt($request->input('password'))]);
            $user = User::create(array_filter($data)); // 过滤掉null元素

            if ($user) {
                $role = Role::find($request->input('role'));

                if (empty($role)) {
                    throw new \Exception('找不到该身份信息');
                }
                $user->assignRole($role);
            } else {
                throw new \Exception('用户注册失败，请重试');
            }

            DB::commit();
            return $this->created('用户注册成功');
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->failed($exception->getMessage());
        }
    }
}
